
package logic.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import logic.beans.User;
import logic.forms.LoginForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import controller.SEISaudeDefaultFacade;

public class LoginAction extends SEISaudeAction {
	@Override
	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception {
		if (checkUserLogged(request)) return mapping.findForward("home");
		
		ActionMessages errors = getErrors(request);
		String actionParam = mapping.getParameter();
		String forwardKey = "ok";
		
		if (actionParam != null) {
			if (actionParam.equals("login")) {
				SEISaudeDefaultFacade<User,Long> facade = SEISaudeDefaultFacade.getInstance(User.class);
				LoginForm myForm = (LoginForm)form;
				if (facade.verifyAccount(myForm.getUserName(),myForm.getPassword())) {
					HttpSession session = request.getSession(true);
					session.setAttribute("userName",myForm.getUserName());
				} else {
					errors.add("login error",new ActionMessage("login.error.wrongUserNameOrPassword",myForm.getUserName()));
					forwardKey = "error";
				}
			}
		}
		
		saveErrors(request,errors);
		
		return mapping.findForward(forwardKey);
	}
}
